<template>
  <div id="map">
    <!-- 导航栏 -->
    <div id="nav">
      <img src="@/images/logo.png" alt="" id="logo" />
      <h2>光谷智慧交通系统</h2>
      <!-- v-if 用户为普通用户 -->
      <a-menu v-if="userType == 'normal'" mode="horizontal">
        <a-sub-menu key="sub0">
          <template #title>实时路况</template>
          <a-menu-item @click="queryLoad" key="setting:1">查看路况</a-menu-item>
          <a-menu-item @click="delQueryLoad" key="setting:2">
            清除路况
          </a-menu-item>
        </a-sub-menu>
        <a-menu-item key="sub1" @click="() => $router.push('/viewnotice')">
          查看公告
        </a-menu-item>
        <a-menu-item key="sub2" @click="refLoad.showModal()">
          报告路况
        </a-menu-item>
        <a-sub-menu key="sub3">
          <template #title>工具箱</template>
          <a-menu-item
            key="setting:1"
            @click.stop="
              () => {
                Measure.measureLength(map.value, source.value)
              }
            "
          >
            距离测量
          </a-menu-item>
          <a-menu-item
            key="setting:2"
            @click.stop="
              () => {
                Measure.measureArea(map.value, source.value)
              }
            "
          >
            面积测量
          </a-menu-item>
          <a-menu-item
            key="setting:3"
            @click.stop="
              () => {
                Measure.closeMeasure(map.value, source.value)
              }
            "
          >
            关闭测量
          </a-menu-item>
          <a-menu-item key="setting:4" @click="exportImg">导出图片</a-menu-item>
        </a-sub-menu>
      </a-menu>
      <!-- v-eles 用户为管理员或交管 -->
      <a-menu v-else mode="horizontal">
        <a-sub-menu key="sub0">
          <template #title>实时路况</template>
          <a-menu-item @click="queryLoad" key="setting:1">查看路况</a-menu-item>
          <a-menu-item @click="delQueryLoad" key="setting:2">
            清除路况
          </a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="sub1">
          <template #title>视频监控</template>
          <a-menu-item @click="cctvRef.handleCCTV()" key="setting:1">
            查看监控
          </a-menu-item>
          <a-menu-item @click="cctvRef.handleCancelCCTV()" key="setting:2">
            取消查看
          </a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="sub2">
          <template #title>事故多发地</template>
          <a-menu-item @click="hotMapRef.addHotMap()" key="setting:1">
            查看事故
          </a-menu-item>
          <a-menu-item @click="hotMapRef.delHotMap()" key="setting:2">
            取消查看
          </a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="sub3">
          <template #title>事件管理</template>
          <a-menu-item
            key="setting:1"
            @click="addDraw({ type: 'Box', callback: drawSuccess })"
          >
            事件拉框查询
          </a-menu-item>
          <a-menu-item
            key="setting:2"
            @click="addDraw({ type: 'Point', callback: drawEventSuccess })"
          >
            事件添加
          </a-menu-item>
          <a-menu-item key="setting:3" @click="handleQuerryAll">
            所有事件
          </a-menu-item>
          <a-menu-item key="setting:4" @click="removeDraw">
            关闭拉框查询
          </a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="sub4">
          <template #title>公告管理</template>
          <a-menu-item
            key="setting:4"
            @click="() => $router.push('/viewnotice')"
          >
            查看公告
          </a-menu-item>
          <a-menu-item key="setting:5" @click="addAnn">发布公告</a-menu-item>
        </a-sub-menu>
        <a-menu-item key="sub5" @click="loadInfoRef.showModal()">
          路况信息
        </a-menu-item>
        <a-sub-menu key="sub6">
          <template #title>工具箱</template>
          <a-menu-item
            key="setting:6"
            @click.stop="
              () => {
                Measure.measureLength(map.value, source.value)
              }
            "
          >
            距离测量
          </a-menu-item>
          <a-menu-item
            key="setting:7"
            @click.stop="
              () => {
                Measure.measureArea(map.value, source.value)
              }
            "
          >
            面积测量
          </a-menu-item>
          <a-menu-item
            key="setting:8"
            @click.stop="
              () => {
                Measure.closeMeasure(map.value, source.value)
              }
            "
          >
            关闭测量
          </a-menu-item>
          <a-menu-item key="setting:9" @click="exportImg">导出图片</a-menu-item>
        </a-sub-menu>
      </a-menu>
      <div>
        <!-- 普通用户搜索 -->
        <a-input-search
          v-if="userType == 'normal'"
          class="search-event"
          v-model:value="normalvalue"
          placeholder="请输入事件类型"
          enter-button
          @search="onSearch"
        ></a-input-search>
        <!-- 交管用户搜索 -->
        <a-input-group v-else compact>
          <a-select
            ref="select"
            v-model:value="optionValue"
            style="width: 120px"
            :options="options"
            :field-names="{ label: 'name', value: 'id' }"
          ></a-select>
          <a-input
            v-model:value="queryKey"
            style="width: 50%"
            @keyup.enter="handleQuery"
          />
        </a-input-group>
      </div>

      <a-dropdown>
        <a class="ant-dropdown-link" @click.prevent>
          <img src="@/images/user.png" alt="" id="user" />
        </a>
        <template #overlay>
          <a-menu>
            <a-menu-item id="username">
              {{ username }}
            </a-menu-item>
            <a-menu-item v-if="userType == 'admin'">
              <a href="http://127.0.0.1:5174/home">用户管理</a>
            </a-menu-item>
            <a-menu-item>
              <a href="" @click="logout">退出登录</a>
            </a-menu-item>
            <!-- <a-menu-item>
              <a href="" @click="changePassword">修改密码</a>
            </a-menu-item> -->
          </a-menu>
        </template>
      </a-dropdown>
    </div>

    <a-modal
      v-model:visible="visible"
      width="1300px"
      title="事件列表"
      cancelText="关闭"
      okText="查看所有事件统计图"
      @cancel="visible = false"
      @ok="handleEchart"
    >
      <EventList :data="data" @changeStatus="changeStatus" />
    </a-modal>
    <!-- 弹框显示添加事件列表 -->
    <a-modal
      v-model:visible="addVisible"
      width="400px"
      title="新增事件"
      okText="新增"
      cancelText="取消"
      @ok="handleAdd"
    >
      <AddEvent ref="addChild" />
    </a-modal>
    <!-- 弹框显示Echarts -->
    <a-modal
      v-model:visible="echartsVisible"
      width="900px"
      title="事件统计图"
      okText="确认"
      cancelText=""
      @ok="echartsVisible = false"
    >
      <Echarts :data="data" />
    </a-modal>
    <!-- 路由出口 -->
    <router-view class="router-view" />

    <!-- 报告路况 -->
    <ReportEvents ref="refLoad" />
    <!-- 基础控件 -->
    <ToggleLayer @changeLayer="changeLayer" />
    <!-- 图例 -->
    <BasicLegend v-show="store.showStore.$state.isShow" />
    <!-- 热力图 -->
    <HotMap ref="hotMapRef" :map="map.value" />
    <!-- 目录树 -->
    <DirectoryTree
      id="directory_tree"
      :map="map.value"
      :docLayer="docLayer.value"
      v-if="userType != 'normal'"
    />
    <!-- 摄像头 -->
    <CCTV ref="cctvRef" :map="map.value" />
    <!-- 路况信息 -->
    <LoadInformation ref="loadInfoRef" />
    <!-- 存放坐标的容器 -->
    <div id="position"></div>
    <!-- 添加公告 -->
    <Announce
      :visible="visible_notice"
      :attrs="attrs"
      @submit="onSubmit"
      @cancel="cancel"
    />
  </div>
</template>

<script setup>
import useQueryLoad from '@/js/queryload.js'
import ToggleLayer from '@/components/ToggleLayer.vue'
import BasicLegend from '@/components/BasicLegend.vue'
import HotMap from '@/components/HotMap.vue'
import DirectoryTree from '@/components/DirectoryTree.vue'
import ReportEvents from '@/components/ReportEvents.vue'
import CCTV from '@/components/CCTV.vue'
import LoadInformation from '@/components/LoadInformation.vue'
import { ref, onMounted, reactive, nextTick, toRaw, watch, h } from 'vue'
import useInitMap from './initMap.js'
import appStore from '@/store/index.js'
import { notification, Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import Announce from '@/components/Announce.vue'
import Measure from '@/utils/Measure.js'
import addAounce from '@/utils/addAounce.js'
import { saveAs } from 'file-saver'
import { storeToRefs } from 'pinia'

import { useUserStore } from '@/store/useUserStore.js'
const userStore = useUserStore()
const { username, userType } = storeToRefs(userStore)
// 路由部分
import { useRouter } from 'vue-router'
const $router = useRouter()
// 封装的请求
import $verify from '@/request/verify.js'
import $api from '@/request/api.js'

const loadInfoRef = ref()
let value = ref('')
let value1 = ref('碰撞')
let attrs = ref([]) //物业名称及电话
let visible_notice = ref(false) //公告添加框
onMounted(() => {
  initMap()
})

//  导出图片
function exportImg() {
  map.value.once('postcompose', function (event) {
    const canvas = event.context.canvas
    canvas.toBlob(function (blob) {
      saveAs(blob, 'map.png')
    })
  })
  map.value.rederSync
}

// 退出登录
function logout() {
  $verify.toLogout({ username: username.value }).then((res) => {})
  $router.push({ path: '/login' })
  localStorage.setItem('isLogin', '')
}

function changePassword() {
  // ---------------
}

// 发布公告
function addAnn() {
  // 获取物业和电话
  addAounce.announce(map.value, source.value, lineLayer.value, attrs)
}

// 根据是否获取到物业信息来确认发布公告
watch(attrs, function (value, oldvalue) {
  visible_notice.value = true
})

const openNotification = () => {
  notification.open({
    description: '请输入公告标题或内容！',
    icon: () =>
      h(ExclamationCircleOutlined, {
        style: 'color: red',
      }),
  })
}

function onSubmit(content, title) {
  if (!content || !title) {
    openNotification()
    return
  }
  $api.addNotice({ content, title, username: username.value }).then((res) => {
    const { code, message } = res
    if (code == 200) {
      Modal.success({
        content: message,
      })
      // map.value.getLayers().pop()
      map.value.getLayers().pop() //清除剪裁的区域
    }
  })
  visible_notice.value = false
}

function cancel() {
  visible_notice.value = false
  map.value.getLayers().pop() //清除剪裁的区域
}

const store = appStore
let res = ref(null)
// 接受CCTV子组件的方法
const cctvRef = ref(null)
const hotMapRef = ref(null)
const refLoad = ref(null)
const { initMap, changeLayer, map, docLayer, lineLayer, source } = useInitMap()
const { queryLoad, delQueryLoad } = useQueryLoad(map)
let normalvalue = ref('')

// 童琦洪负责部分
// ------------------- 事件查询相关
import useDrawHook from './Hooks/useDrawHook'
import useEventHook from './Hooks/useEventHook'

// 导入表单
import EventList from '@/components/EventList.vue'
let visible = ref(false)
let data = ref([])
// 导入表单
import AddEvent from '@/components/AddEvent.vue'
let addVisible = ref(false)
const { drawLayer, drawSource, addDraw, removeDraw } = useDrawHook(map)
const {
  queryByBox,
  queryByAttr,
  changeStatus,
  queryAll,
  options,
  optionValue,
} = useEventHook(map)
let queryKey = ref('')
// 拉框完成后执行的回调函数
let addChild = ref(null)
let point = reactive([])
const drawSuccess = (e) => {
  visible.value = true
  drawSource.value.clear()
  let geom = e.feature.values_.geometry
  queryByBox({ geom, callback: querySuccess })
}
const drawEventSuccess = (e) => {
  addVisible.value = true
  point.value = e.feature.getGeometry().flatCoordinates
}
// 点击新增按钮后触发的事件
const handleAdd = () => {
  addVisible.value = false
  setTimeout(() => {
    addChild.value.add(point, docLayer)
  }, 1)
  // 使用nextTick 等子组件挂载完成后调用
  // nextTick(() => {
  //   addChild.value.add()
  // })
  // addChild.value.add()
}
// 普通用户查询
const onSearch = (val) => {
  let sql = `事件类型 like '%${val}%'`
  queryByAttr({ where: sql, callback: querySuccess })
  visible.value = true
}

// 关键字查询
const handleQuery = () => {
  let sql = `${optionValue.value} like '%${queryKey.value}%'`
  queryByAttr({ where: sql, callback: querySuccess })
  visible.value = true
}
// 查询所有
const handleQuerryAll = () => {
  queryAll({ callback: querySuccess })
  visible.value = true
}
// 引入Echarts的组件
import Echarts from '@/components/EventEcharts.vue'
let echartsVisible = ref(false)
// echart图
const handleEchart = () => {
  echartsVisible.value = true
  queryAll({ callback: querySuccess })
}
// 查询完成后的回调函数
const querySuccess = (e) => {
  data.value = []
  const FldName = e.AttStruct.FldName
  e.SFEleArray.map((item) => {
    let obj = {}
    for (let i = 0; i < item.AttValue.length; i++) {
      obj = Object.assign(
        obj,
        { FID: item.FID },
        { position: item.fGeom.PntGeom[0].Dot },
        { [FldName[i]]: item.AttValue[i] }
      )
    }
    data.value.push(obj)
  })
}
</script>
<style scoped>
#nav {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  height: 9vh;
  line-height: 9vh;
  width: 100%;
  padding-left: 1vw;
  background: white;
  font-weight: 600;
  z-index: 888;
}

.ant-menu-horizontal {
  color: #655e5e;
}

#nav h2 {
  font-weight: 700;
}

#logo {
  width: 5vw;
  margin-right: 0.5vw;
}

/* 普通用户搜索框 */
.search-event[data-v-a763a6ae] {
  position: fixed;
  top: 1.5vh;
  right: 8vw;
  width: 25vw;
}

/* 用户头像 */
.ant-dropdown-link {
  position: absolute;
  top: -3px;
  right: 19px;
  width: 3vw;
}

#username {
  background: #1890ff;
}

/* 头像 */
.ant-dropdown-link {
  position: absolute;
  top: -6px;
  right: 50px;
}
.ant-dropdown-link #user {
  width: 3vw;
}

/* 搜索框 */
.ant-input-group.ant-input-group-compact {
  display: block;
  position: fixed;
  width: 20vw;
  height: 10vh;
  top: 8px;
  right: 90px;
}
/* 鼠标位置 */
#position {
  position: fixed;
  bottom: 5px;
  left: 48vw;
  color: white;
  z-index: 999;
}

/* 复位 */
:deep .ol-zoom-extent {
  top: 46vh;
  left: 7px;
}

/* 鹰眼图 */
:deep .ol-overviewmap {
  position: fixed;
  background: rgba(255, 255, 255, 0.8);
}

/* 比例尺 */
:deep .ol-scale-line-inner {
  position: fixed;
  bottom: 8px;
  left: 15vw;
  padding: 1px 1px;
  background: rgba(119, 156, 207, 0.5);
  color: white;
}

/* 目录树 */
#directory_tree .ant-tree-icon-hide {
  z-index: 100;
  top: 35vh;
  right: 1vw;
  position: fixed;
  width: 200px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
}

/**
  * 提示框的样式信息
  */
:deep .tooltip {
  position: relative;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
  color: white;
  padding: 4px 8px;
  opacity: 0.7;
  white-space: nowrap;
}

:deep .tooltip-measure {
  opacity: 1;
  font-weight: bold;
}

:deep .tooltip-static {
  background-color: rgb(52, 238, 249);
  color: black;
  border: 1px solid white;
}

:deep .tooltip-measure:before,
.tooltip-static:before {
  border-top: 6px solid rgba(0, 0, 0, 0.5);
  border-right: 6px solid transparent;
  border-left: 6px solid transparent;
  content: '';
  position: absolute;
  bottom: -6px;
  margin-left: -7px;
  left: 50%;
}

:deep .tooltip-static:before {
  border-top-color: #ffcc33;
}
</style>
